import { Component } from '@angular/core';
import {FormControl, FormGroup, NonNullableFormBuilder, Validators} from "@angular/forms";
import {ActivatedRoute, ParamMap, Router} from "@angular/router";
import {select, Store} from "@ngrx/store";
import {ListActions} from "../store/actions/list.actions";
import {List} from "../store/model/list.model";
import {selectCurrentRoute, selectQueryParams, selectRouter} from "../store/selectors/router.selectors";
import {RouterReducerState} from "@ngrx/router-store";

@Component({
  selector: 'app-update-info',
  templateUrl: './update-info.component.html',
  styleUrls: ['./update-info.component.less']
})
export class UpdateInfoComponent {
  constructor(
    private fb: NonNullableFormBuilder,
    private route: ActivatedRoute,
    private router: Router,
    private store: Store<{ list: { list: List[] } }>
  ) {
    this.route.queryParamMap.subscribe((query : ParamMap)=> {
      console.log('query', query)
      const id = query.get('id') || 0
      const name = query.get('name') || ''
      const age = query.get('age') || 0
      this.validateForm.get('id')?.setValue(+id)
      this.validateForm.get('name')?.setValue(name)
      this.validateForm.get('age')?.setValue(+age)
    })
    // 路由放在Store里面，每次路由跳转，都会进入到这方法里面。
    store.pipe(select(selectQueryParams)).subscribe((routerState: any) => {
      // 处理选择的 router state
      console.log('routerState',routerState)
    });
  }

  validateForm: FormGroup<{
    id: FormControl<number>;
    name: FormControl<string>;
    age: FormControl<number>;
  }> = this.fb.group({
    id: [0, [Validators.required]],
    name: ['', [Validators.required]],
    age: [0, [Validators.required]],
  });

  submit(): void {
    if (this.validateForm.valid) {
      console.log('submit', this.validateForm.value);
      // this.store.dispatch(ListActions.updateLists({
      //   data: {
      //     id: this.validateForm.value.id || 0,
      //     name: this.validateForm.value.name || '',
      //     age: this.validateForm.value.age || 0
      //   },
      // }))
      this.store.dispatch(ListActions.updateEntity({
        data: {
          id: this.validateForm.value.id || 0,
          name: this.validateForm.value.name || '',
          age: this.validateForm.value.age || 0
        },
      }))
      this.router.navigateByUrl('/list')
    } else {
      Object.values(this.validateForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({onlySelf: true});
        }
      });
    }
  }

  back() {
    this.router.navigateByUrl('/list')
  }
}
